/**
 * Copyright (c) 2005-2012 https://github.com/zhangkaitao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.apanal.qlife.common.jcaptcha;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import com.apanal.qlife.common.util.PropertieUtil;

/**
 * 验证码验证的Shiro过滤器
 * 
 * 
 * @author shuliangxing
 * 
 * @date 2015-9-10下午5:38:51
 */
public class JCaptchaValidateFilter extends AccessControlFilter {

	private boolean jcaptchaEbabled = true;// 是否开启验证码支持

	private String jcaptchaParam = "jcaptchaCode";// 前台提交的验证码参数名

	private String failureKeyAttribute = "shiroLoginFailure"; // 验证码验证失败后存储到的属性名

	public void setJcaptchaEbabled(boolean jcaptchaEbabled) {
		this.jcaptchaEbabled = jcaptchaEbabled;
	}

	public void setJcaptchaParam(String jcaptchaParam) {
		this.jcaptchaParam = jcaptchaParam;
	}

	public void setFailureKeyAttribute(String failureKeyAttribute) {
		this.failureKeyAttribute = failureKeyAttribute;
	}

	@Override
	protected boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) throws Exception {
		// 1、设置验证码是否开启属性，页面可以根据该属性来决定是否显示验证码
		request.setAttribute("jcaptchaEbabled", jcaptchaEbabled);

		HttpServletRequest httpServletRequest = WebUtils.toHttp(request);

		HttpSession session = httpServletRequest.getSession(true);
		// 登录界面显示次数
		Integer loginCount = (Integer) session.getAttribute("loginCount");
		if (loginCount == null) {
			loginCount = 0;
		}
		loginCount++;
		session.setAttribute("loginCount", loginCount);

		// 第几次显示验证码
		int indexShowCaptcha = Integer.valueOf(PropertieUtil
				.getPropertie("indexShowCaptcha"));
		session.setAttribute("indexShowCaptcha", indexShowCaptcha);

		// 2、判断验证码是否禁用 或不是表单提交或在不显示验证码之内（允许访问）
		if (jcaptchaEbabled == false
				|| !"post".equalsIgnoreCase(httpServletRequest.getMethod())
				|| loginCount <= indexShowCaptcha) {
			return true;
		}
		// 3、此时是表单提交，验证验证码是否正确
		return JCaptcha.validateResponse(httpServletRequest,
				httpServletRequest.getParameter(jcaptchaParam));
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		// 验证码错误
		String error = "jCaptcha.error";
		HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
		// 如何验证码为空, 提示验证码必须
		if (httpServletRequest.getParameter(jcaptchaParam) == null) {
			error = "jCaptcha.mustError";
		}
		// 如果验证码失败了，存储失败key属性
		request.setAttribute(failureKeyAttribute, error);
		return true;
	}
}
